package cn.wtg.kotlinlib.baseUi

import androidx.appcompat.app.AppCompatActivity
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.schedule

/**
 * author: wtg
 * time: 2022/11/28
 * desc: 基础类
 */
open class BaseActivity : AppCompatActivity() {
    protected var TAG: String = this.javaClass.name
    private var loadingPopupView: LoadingPopupView? = null

    protected fun showLoading(title: String) {
        CoroutineScope(Dispatchers.Main).launch {
            if (loadingPopupView == null) {
                loadingPopupView = XPopup.Builder(this@BaseActivity).dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false).asLoading()
            }
            loadingPopupView?.setTitle(title)
            if (!loadingPopupView?.isShow!!) {
                loadingPopupView!!.show()
            }
        }
    }

    protected fun showLoading() {
        showLoading("")
    }

    protected fun closeLoading() {
        Timer().schedule(200) {
            CoroutineScope(Dispatchers.Main).launch {
                if (loadingPopupView != null && loadingPopupView!!.isShow) {
                    loadingPopupView!!.dismiss()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        closeLoading()
        loadingPopupView = null
    }
}